package com.hucsmn.stumansys.servlet.admin;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.hucsmn.stumansys.entity.Admin;
import com.hucsmn.stumansys.service.AdminService;
import com.hucsmn.stumansys.utils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 管理员注册 API。
 *
 * 接收 HTTP 参数
 *      name    管理员用户名。
 *      crypt   密码哈希值。十六进制表示的 SHA-256 字符串。
 *
 * 响应 JSON 数据
 *      code    状态码。0 表示注册成功，1 表示注册失败，2 表示权限错误。
 *      msg     操作出错原因。
 *
 * 备注
 *      要求 session.login 必须是 Admin 且非空，只有管理员可以创建管理员。
 *
 * @author hucsmn
 */
@WebServlet("/api/admin/register")
public class AdminRegisterServlet extends HttpServlet {
    private final AdminService adminService = AdminService.getInstance();
    private final Gson gson = new GsonBuilder().create();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        Admin admin = new Admin();
        admin.setName(ConvertUtils.normalizeText(request.getParameter("name")));
        admin.setCrypt(ConvertUtils.normalizeText(request.getParameter("crypt")));

        JsonObject result = new JsonObject();
        HttpSession session = request.getSession();
        if (!(session.getAttribute("login") instanceof Admin)) {
            result.addProperty("code", 2);
            result.addProperty("msg", "没有权限");
        } else if (!adminService.register(admin)) {
            result.addProperty("code", 1);
            if (ConvertUtils.validateAdmin(admin)) {
                result.addProperty("msg", "账户名已存在");
            } else {
                result.addProperty("msg", "账户名或密码格式不正确");
            }
        } else {
            result.addProperty("code", 0);
            result.addProperty("msg", "");
        }

        PrintWriter out = response.getWriter();
        out.write(gson.toJson(result));
        out.flush();
        out.close();
    }
}
